package com.wowkids.common;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author DoDayum
 * @Date 2024-03-05-22:36
 */
public class JWTUtil {

    private static final String KEY = "the_key";

    public static String encode(String input) {

        JWTCreator.Builder jwtBuilder = JWT.create();
        Map<String, Object> headers = new HashMap<>();
        headers.put("typ", "jwt");   //设置token的type为jwt
        headers.put("alg", "hs256");  //表明加密的算法为HS256
        return jwtBuilder.withHeader(headers)
                .withClaim("user", input)
                //token失效时间，这里为一天后失效
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24))
                //设置该jwt的发行时间，一般为当前系统时间
                .withIssuedAt(new Date(System.currentTimeMillis()))
                //进行签名，选择加密算法，以一个字符串密钥为参数
                .sign(Algorithm.HMAC256(KEY));
    }

    public static Map<String, String> decode(String token) {
        DecodedJWT decode = JWT.require(Algorithm.HMAC256(KEY)).build().verify(token);
        //可以一次性获取所有的自定义参数，返回Map集合
        Map<String, String> response = new HashMap<>();
        Map<String, Claim> claims = decode.getClaims();
        claims.forEach((k, v) -> response.put(k, v.asString()));
        return response;
    }

    /**
     * JWT测试使用
     */
    public static void main(String[] args) throws InterruptedException {
        String token = JWTUtil.encode("qwe");
        System.out.println("加密后的\t" + token);
        Thread.sleep(3);
        Map<String, String> decode = JWTUtil.decode(token);
        System.out.println(decode);
    }

}
